package server

import (
	"fmt"
	"gitee.com/game_diamond/protocols"
	"qiniupkg.com/x/errors.v7"
)

var (
	errFuncNotExist  = errors.New("func not exist")
	errSceneNotExist = errors.New("scene not exist")
)

//action
type wsActionFunc func(userId int, body *protocols.WebSocketBody)

//scene
type wsSceneFunc func(userId int)

//on event
type wsOnCloseFunc func(userId int)
type wsOnConnectFunc func(userId int)

var (
	wsActionMap = make(map[int]map[int]wsActionFunc)
	wsSceneMap  = make(map[int]map[int]wsSceneFunc)

	//on event
	wsOnConnect = make(map[int][]wsOnConnectFunc)
)

func RegisterWsAction(actor int, action int, f wsActionFunc) {
	if _, ok := wsActionMap[actor]; !ok {
		wsActionMap[actor] = make(map[int]wsActionFunc)
	}
	if _, ok := wsActionMap[actor][action]; ok {
		panic(fmt.Sprintf("RegisterWebscoketActionStudent:: action:%v exist", action))
	}
	wsActionMap[actor][action] = f
}

func GetWsAction(actor int, action int) (wsActionFunc, error) {
	if _, ok := wsActionMap[actor]; !ok {
		return nil, errFuncNotExist
	}
	if f, ok := wsActionMap[actor][action]; ok {
		return f, nil
	}
	return nil, errFuncNotExist
}

func RegisterWsScene(actor int, sceneId int, f wsSceneFunc) {
	if _, ok := wsSceneMap[actor]; !ok {
		wsSceneMap[actor] = make(map[int]wsSceneFunc)
	}
	if _, ok := wsSceneMap[actor][sceneId]; ok {
		panic(fmt.Sprintf("RegisterWebscoketActionStudent:: sceneId:%v exist", sceneId))
	}
	wsSceneMap[actor][sceneId] = f
}

func GetWsScene(actor int, sceneId int) (wsSceneFunc, error) {
	if _, ok := wsSceneMap[actor]; !ok {
		return nil, errSceneNotExist
	}
	if f, ok := wsSceneMap[actor][sceneId]; ok {
		return f, nil
	}
	return nil, errSceneNotExist
}

func RegisterWsOnConnect(actor int, f wsOnConnectFunc) {
	if _, ok := wsOnConnect[actor]; !ok {
		wsOnConnect[actor] = make([]wsOnConnectFunc, 0)
	}
	wsOnConnect[actor] = append(wsOnConnect[actor], f)
}
